package gengine.serverside;

import gengine.common.misc.BaseClientThread;
import gengine.common.misc.ClientInfo;
import gengine.common.packets.BasePacket;
import gengine.common.packets.MessagePacket;
import gengine.common.packets.PacketTypeEnum;
import gengine.common.packets.PingPacket;

import java.io.IOException;
import java.net.Socket;
import java.util.Date;

/**
 * User: arseniy
 * Date: 21.12.11
 */
public class ServerClient extends BaseClientThread {
    private ServerThread server;
    private long ping;
    ClientInfo clientInfo;

    public ServerClient(Socket socket, ServerThread server, int id) throws IOException {
        super(socket, id);
        this.server = server;
        clientInfo = new ClientInfo();
        clientInfo.setId(id);
        clientInfo.setName("Unnamed");
        clientInfo.setConnectedAt(new Date());
        clientInfo.setIpAddress(socket.getRemoteSocketAddress().toString());
    }

    @Override
    protected void ProcessPacket(BasePacket packet) {
        PacketTypeEnum type = packet.getPacketType();
        switch (type) {
            case ClientInfoPacket: {
                server.BroadcastPacket(packet);
                break;
            }
            case Message: {
                MessagePacket message = (MessagePacket) packet;
                int id = message.getTargetId();
                if (id == 0)
                    server.BroadcastPacket(message);
                else {
                    ServerClient target = server.getClientById(message.getClientId());
                    if (target != null)
                        target.sendPacketImmediately(message);
                }
            }
            case Ping: {
                if (type==PacketTypeEnum.Ping) {
                    PingPacket pp = (PingPacket)packet;
                    ServerClient sc = server.getClientById(pp.getClientId());
                    //pong
                    if (pp.answer==0) {
                        pp.answer=1;
                        sc.sendPacketImmediately(pp);
                        return;
                    } else {
                        //our ping
                        sc.ping = System.currentTimeMillis()-pp.getCreationTime();
                    }
                }
            }
        }
    }
}
